package com.polaris.live.ui.message

import android.os.Bundle
import android.view.View
import androidx.core.os.bundleOf
import com.blankj.utilcode.util.StringUtils
import com.bumptech.glide.Glide
import com.polaris.live.R
import com.polaris.live.common.R.color
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.constant.BizEventConst
import com.polaris.live.common.event.EventMessage
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.base2.BaseVbActivity
import com.polaris.live.common.network.parseState
import com.polaris.live.common.util.ImmersionBarBuilder
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.constant.LiveConst
import com.polaris.live.constant.UserConst
import com.polaris.live.databinding.ActivityMessageBinding
import com.polaris.live.im.manager.RouterControlManager
import com.polaris.live.im.sfs.SYSTEM_USER_ID
import com.polaris.live.interface_bag.PAGViewListener
import com.polaris.live.popup.GlobalPopupManager
import com.polaris.live.resp.back_resp.InfoOtherResp
import com.polaris.live.resp.back_resp.toUserBasicVo
import com.polaris.live.translation.R.string
import com.polaris.live.ui.message.fragment.MessageSingleFragment
import com.polaris.live.ui.message.proxy.MessageListenerProxy
import com.polaris.live.utils.CommonUtils
import com.polaris.live.utils.LiveUtils
import com.polaris.live.utils.StartCallProxy
import com.polaris.live.utils.fragment.attachFragment
import com.polaris.live.utils.getIntOrString
import com.polaris.live.utils.getLongOrString
import com.polaris.live.utils.image.ImageUtils
import com.polaris.live.utils.image.loadImage
import com.polaris.live.utils.image.normal
import com.polaris.live.utils.photo.PicturePreview
import com.polaris.live.utils.route.RouterUtils
import com.polaris.live.viewmodel.message.MessageViewModel
import com.polaris.live.widget.pag.AddFollowView.Companion.LIVE_ADD_FOLLOWE_ALPHA
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.libpag.PAGView

/**
 * MessageActivity
 *
 * @author Created by 半仙 on 2023/9/4/004 14:57
 */
class MessageActivity : BaseVbActivity<MessageViewModel, ActivityMessageBinding>() {

    private val mOtherId by lazy { intent.getLongOrString("userId", 0) }
    private val mNickname by lazy { intent.getStringExtra("nickname") }
    private val mAvatar by lazy { intent.getStringExtra("avatar") }
    private val mAvatarFrame by lazy { intent.getStringExtra("avatarFrame") }
    private val mChatBubble by lazy { intent.getStringExtra("chatBubble") }
    private val mPage by lazy { intent.getIntOrString("page", UserConst.From.UNKNOWN) }

    private val mFragment: MessageSingleFragment by lazy {
        supportFragmentManager.attachFragment(R.id.fl_fragment_single) {
            MessageSingleFragment().apply {
                arguments = bundleOf(
                    "otherId" to mOtherId,
                    "avatar" to mAvatar,
                    "avatarFrame" to mAvatarFrame,
                    "chatBubble" to mChatBubble,
                )
            }
        }
    }

    private lateinit var mOnClickProxy: MessageListenerProxy
//    private lateinit var mUserStateProxy: UserStatePlayerProxy<MessageViewModel>

    private var mOtherInfo: InfoOtherResp? = null

    override fun ImmersionBarBuilder.buildImmersionBar() {
        if (mOtherId == SYSTEM_USER_ID) {
            setNavigationBarColor(color.color_f8f9fa)
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        EventBus.getDefault().register(this)
        mOnClickProxy = MessageListenerProxy(mOtherId, mNickname, this, mBinding, mViewModel, mPage)
//        mUserStateProxy = UserStatePlayerProxy(
//            this,
//            mViewModel,
//            mOtherId,
//            LiveActivityIdentifier.MESSAGE_ACTIVITY
//        )

        mFragment.setOnSetStateNormal {
            mBinding.editView.setStateNormal()
        }

        mBinding.ivFollower.apply {
            setPathType(LIVE_ADD_FOLLOWE_ALPHA)
            addListener(object : PAGViewListener {
                override fun onAnimationEnd(p0: PAGView?) {
                    super.onAnimationEnd(p0)
                    mBinding.ivFollower.visibility = View.GONE
                }
            })
            setRepeatCount(1)
        }

        initObserver()
        initListener()

        RouterUtils.routerGotoChild(this)
    }

    private fun initObserver() {
        if (mNickname != null) {
            mBinding.userName.text = mNickname
            mBinding.userName.setNicknameColor(
                null,
                R.color.color_ff0b0123
            )
        }
        //这里这么写主要是想获取完资料后在展示消息   后续考虑更换写法
        mViewModel.infoOtherLiveData.observe(this) { resultState ->
            parseState(resultState, {
                setInfoOtherToUi(it)
            })

        }
        //添加关注
        mViewModel.addFollowerLiveData.observe(this) { resultState ->
            parseState(resultState, {
                ToastGravity.showGravity(string.follower_succeed)
                mBinding.ivFollower.play()
            }, {
                ToastGravity.showGravity(it.errorMsg)
            })
        }
        //路由监听
        RouterControlManager.observeListener(this) { key, ext ->
            when (key) {
                RouterControlManager.ROUTER_GIFT -> { //礼物盘拉起
                    mOnClickProxy.showGiftDialog()
                }
            }
        }
    }

    /**
     * 获取数据后更新
     */
    private fun setInfoOtherToUi(user: InfoOtherResp) {
        mOtherInfo = user
        mFragment.setCompInfo(UserManager.getUser().compInfo == 1)
        mBinding.userName.text = user.nickname
        mBinding.userName.setNicknameColor(
            user.decoration?.nicknameColor,
            R.color.color_ff0b0123
        )
        if (user.relation?.followed != true) {
            mBinding.ivFollower.visibility = View.VISIBLE
        } else {
            mBinding.ivFollower.visibility = View.GONE
        }
        mBinding.tvAboutMe.text = user.profile.aboutMe
        if (user.profile.aboutMe?.isNotEmpty() == true) {
            mBinding.tvAboutMe.visibility = View.VISIBLE
        } else {
            mBinding.tvAboutMe.visibility = View.GONE
        }
        mFragment.setAvatar(user.avatar, user.decoration?.avatarFrame, user.decoration?.chatBubble)
        mFragment.setInfoOtherResp(user)

//        if (canShowTopLayout(user)) {
        val photoUrls = buildList {
            user.photos.forEach { add(it.url) }
        }
        if (photoUrls.size < 2) {
            mBinding.layoutHeader.visibility = View.GONE
            mBinding.tipLl.visibility = View.GONE
            mBinding.tvAboutMe.visibility = View.GONE
        } else {
            mBinding.layoutHeader.visibility = View.VISIBLE
            mBinding.tipLl.visibility = View.VISIBLE
            mBinding.tvAboutMe.visibility = View.VISIBLE
        }

        //播放相关
        if (user.live?.liveStreamId != null) {
//                mBinding.videoCard.visibility = View.VISIBLE
        }
        Glide.with(this)
            .loadImage(user.coverPhoto?.url ?: user.avatar)
            .centerCrop()
            .into(mBinding.ivStreamCover)

//            mUserStateProxy.init(user, mBinding.stream, object : OnLivePlayListenerImpl() {
//                override fun onPlayStop() {
//                    mBinding.ivStreamCover.visibility = View.VISIBLE
//                }
//
//                override fun onPlayerRenderVideoFirstFrame() {
//                    if (mBinding.videoCard.visibility != View.VISIBLE) {
//                        mOtherInfo?.also {
//                            updateTopLayout(it, photoUrls)
//                        }
//                    }
//                    mBinding.videoCard.visibility = View.VISIBLE
//                    mBinding.ivStreamCover.visibility = View.GONE
//                }
//
//                override fun onRemoteSpeakerStateUpdate(state: ZegoRemoteDeviceState) {
//                    if (state == ZegoRemoteDeviceState.OPEN) {
//                        if (mBinding.videoCard.visibility != View.VISIBLE) {
//                            mOtherInfo?.also {
//                                updateTopLayout(it, photoUrls)
//                            }
//                        }
//                        mBinding.videoCard.visibility = View.VISIBLE
//                        mBinding.ivStreamCover.visibility = View.GONE
//                    }
//                }
//
//            })
//            mUserStateProxy.observe {
//                //修改对方的状态
//            }
        updateTopLayout(user, photoUrls)

        mBinding.saSex.setSexAndAge(user.sex, user.birthday)
        mBinding.lvLanguage.setLanguage(user.profile.secondLanguage)
        mBinding.cvCountry.setCountry(user.profile.country)

        if (user.flag.official == 1L) {
            mBinding.ivOfficial.visibility = View.VISIBLE
        } else {
            mBinding.ivOfficial.visibility = View.GONE
        }

        mBinding.levelRich.setRichsLevel(user.account.richs)
        mBinding.levelCharm.setCharmsLevel(user.account.charms)
//        }
        mBinding.vipView.setVipLevel(user.profile.vipLevel)
        if (mFragment.isToBottom()) {
            mFragment.scrollToBottom()
        }
        mFragment.showFadingEdge()
    }

    private fun updateTopLayout(user: InfoOtherResp, photoUrls: List<String>) {
//        val viewList = if (user.live?.liveStreamId != null) {
//            mBinding.headerImg3.visibility = View.GONE
//            listOf(mBinding.headerImg1, mBinding.headerImg2, mBinding.headerImgMore)
//        } else {
        mBinding.headerImg3.visibility = View.INVISIBLE
        val viewList = listOf(
            mBinding.headerImg1,
            mBinding.headerImg2,
            mBinding.headerImg3,
            mBinding.headerImgMore
        )
//        }

        viewList.forEachIndexed { index, view ->
            photoUrls.getOrNull(index).also { url ->
                if (url.isNullOrEmpty()) {
                    view.visibility = View.INVISIBLE
                } else if (view.id == R.id.header_img_more) {
                    mBinding.headerRlMore.visibility = View.VISIBLE
                } else {
                    view.visibility = View.VISIBLE
                }

                Glide.with(this)
                    .loadImage(url)
                    .normal()
                    .into(view)

                view.setOnSingleClickListener {
                    toOpenImage(it, user, photoUrls, index)
                }

            }
        }
        if (photoUrls.size <= viewList.size) {
            mBinding.headerMore.visibility = View.GONE
        }
    }

    private fun toOpenImage(view: View, user: InfoOtherResp?, photoUrls: List<String>, index: Int) {
        PicturePreview.with(this)
            .byView(view)
            .setImageUrlList(ArrayList(photoUrls.map { ImageUtils.imgPath(it) }))
            .setIndex(index)
            .setUserInfo(user)
            .go()
    }

    private fun initListener() {
        mBinding.editView.setOnKeyboardListener {
            if (it) {
                mFragment.scrollToBottom()
            }
        }
        mBinding.videoCard.setOnSingleClickListener {
            GlobalPopupManager.showCompletePopup(this) {
                if (mOtherInfo?.live?.liveType == LiveConst.Type.ONLY_LIVE) {
                    mOtherInfo?.let {
                        LiveUtils.toSpectator(it).navigation(this)
                    }
                } else {
                    StartCallProxy.builder(this).startCall(
                        mViewModel,
                        mPage,
                        if (mOtherId != SYSTEM_USER_ID) UserConst.LastFrom.SINGLE else UserConst.LastFrom.SYSTEM_MESSAGE,
                        LiveConst.SenderFrom.MANUAL,
                        mOtherId,
                        mOtherInfo?.toUserBasicVo()
                    )
                }
            }
        }
        mOnClickProxy.setOnSendMessageCallback {
            mViewModel.sendTextMessage(this, mOtherId, it, mFragment.getPushDetailId())
        }
    }

    private fun canShowTopLayout(user: InfoOtherResp) =
        CommonUtils.isMan(UserManager.getUser().sex) && !CommonUtils.isMan(user.sex)

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: EventMessage) {
        when (event.from) {
            BizEventConst.GIFT_POP_CLOSE -> {
                mBinding.editView.setResume(true)
            }
        }
    }

    override fun onResume() {
        super.onResume()
        //系统消息特殊处理
        if (mOtherId == SYSTEM_USER_ID) {
            mBinding.userName.text =
                StringUtils.getString(string.app_name) + " " + StringUtils.getString(string.team)
            mBinding.moreSelect.visibility = View.INVISIBLE
            mBinding.ivFollower.visibility = View.INVISIBLE
            mBinding.editView.visibility = View.GONE
            mBinding.vBottomLine.visibility = View.GONE
        } else {
            mViewModel.getInfoUser(
                mOtherId,
                true,
                UserManager.BASIC_INFORMATION,
                UserManager.RELATIONSHIP_INFORMATION,
                UserManager.ALBUM_INFORMATION,
                UserManager.COVER_INFORMATION,
                UserManager.CALL_INFORMATION,
                UserManager.LIVE_INFORMATION,
                UserManager.DECORATIVE_DISPLAY
            )
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
}